<?php

if(!defined ('TYPO3_MODE'))		die('Access denied.');

//tslib_eidtools::connectDB();

$tempDir = $GLOBALS['_SERVER']['DOCUMENT_ROOT'] . "/fileadmin/enoteserver/temp/";

$response = Array();
switch(t3lib_div::_GET('function')) { 
	case 'customEnoteStatus':
		$id = t3lib_div::_GET('generationID');
		$path = $tempDir . $id;
		if(preg_match("/^[a-f0-9]{128}$/",$id)) {
			if(file_exists($path . ".pdf")) {
				if((time() - filemtime($path . ".pdf")) < 10) {
					$response['status']['code'] = "GENERATING";
				} elseif(!file_exists($path . ".ticket")) {
					$response['status']['code'] = "DONE";
				} else {
					$response['status']['code'] = "GENERATING";
				}
			} elseif(file_exists($path . ".ticket") || (time() - filectime($path . ".tex")) < 20) {
				$queue = exec("ls -1rt " . $tempDir . "*.ticket | grep -n " . $id . " | awk '{split($0,a,\":\"); print a[1]}'");
				if($queue > 1) {
					$response['status'] = Array("code" => "QUEUED", "position" => $queue);
				} else {
					$response['status'] = Array("code" => "GENERATING");
				}
			} else {
				$response['status']['error'][] = "Not found";
			}
		} else {
			$response['status']['error'][] = "Invalid ID supplied";
		}
	break;
	case 'fetchPDF':
		$id = t3lib_div::_GET('generationID');
		$path = $tempDir . $id;
		if(preg_match("/^[a-f0-9]{128}$/",$id)) {
			$localPDF = $path . ".pdf";
			$metaData = json_decode(file_get_contents($path . ".metadata"),true);
			$finalName = $metaData['title'] . " (Rev. ".$metaData['revision'].").pdf";
			if(file_exists($localPDF)) {
				if((time() - filemtime($path . ".pdf")) > 3) {
					$fd = fopen($localPDF, "rb");
					header('Content-Type: application/pdf');
					header('Content-Disposition: attachment; filename="'.$finalName.'"');
					header('Content-Length: ' . filesize($localPDF));
					
					while (!feof($fd)) {
						$buffer = fread($fd, 1024*1024);
						echo $buffer;
						flush();
						ob_flush();
					}

					fclose($fd);

					exit(0);
				}
			}
			echo "En fejl opstod. Forsøg at opdatere siden.";
			exit(0);
		}
		echo "Ugyldigt ID";
		exit(0);
	break;
	default:
		$response['status']['error'][] = "No valid function passed";
}
if($response['status']['error']) {
	$response['status']['code'] = 'ERROR';
}
$json = json_encode($response);
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
header('Content-length: ' . strlen($json));
echo $json;
?>